package com.umeox.watch.moto.dataservice.utils;


import com.tencent.mmkv.MMKV;
import com.umeox.moto.common.utils.GsonUtils;
import com.umeox.watch.moto.dataservice.base.BaseApp;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Rambo 2022/3/28
 * Describe:
 */
public class MMKVUtils {

    public static <T> Boolean setArray(String name,List<T> list) {
        MMKV kv = BaseApp.getInstance().getMmkv();
        if (list == null || list.size() == 0) { //清空
            kv.putInt(name + "size", 0);
            int size = kv.getInt(name + "size", 0);
            for (int i = 0; i < size; i++) {
                if (kv.getString(name + i, null) != null) {
                    kv.remove(name + i);
                }
            }
        } else {
            kv.putInt(name + "size", list.size());
            if (list.size() > 20) {
                list.remove(0);   //只保留后20条记录
            }
            for (int i = 0; i < list.size(); i++) {
                kv.remove(name + i);
                kv.remove(GsonUtils.toJson(list.get(i)));//删除重复数据 先删后加
                kv.putString(name + i, GsonUtils.toJson(list.get(i)));
            }
        }
        return kv.commit();
    }


    public static <T> List<T> getArray(String name, T bean) {
        MMKV kv = BaseApp.getInstance().getMmkv();
        List<T> list = new ArrayList<>();
        int size = kv.getInt(name + "size", 0);
        for (int i = 0; i < size; i++) {
            if (kv.getString(name + i, null) != null) {
                try {
                    list.add((T) GsonUtils.toBean(kv.getString(name + i, null), bean.getClass()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        return list;
    }

}